//
//  KVPullDownRefresh.swift
//  KVPlluDown
//
//  Created by 李康卫 on 16/7/26.
//  Copyright © 2016年 李康卫. All rights reserved.
//

import UIKit


class KVPullDownRefresh: UIView {
    ///PullDownRefresh高度
    let pullDownRefreshHight: CGFloat = 60
    ///刷新的状态
    enum KVPullDownRefreshStatus: Int {
        case Normal
        case Pulling
        case Refreshing
    }
    ///设置代码块回调告诉控制器刷xin
    var refreshBlock: (() -> Void)?
    ///开始刷新
    func beginRefreshing() {
        self.courrentState = .Refreshing
    }
    ///结束刷新
    func endRefreshing() {
        if courrentState == .Refreshing {
            self.courrentState = .Normal
            //移除动画
            self.iconView.layer.removeAllAnimations()
            //隐藏刷新
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.scrollView?.contentInset.top = (self.scrollView?.contentInset.top)! - self.pullDownRefreshHight
            })
            
        }
    }
    ///当前状态
    var courrentState: KVPullDownRefreshStatus = .Normal {
        //状态改变是设置相应的视图
        didSet {
            switch courrentState {
            case .Normal:
                self.iconView.image = UIImage(named: "tableview_pull_refresh")
                lable.text = "下拉刷新"
                iconView.transform = CGAffineTransformIdentity
            case .Pulling:
                //改变箭头的朝向
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                lable.text = "松手刷新"
            case .Refreshing:
                iconView.image = UIImage(named: "tableview_loading")
                self.iconView.transform = CGAffineTransformIdentity
                lable.text = "正在刷新..."
                //增加动漫效果
                
                let animation:CABasicAnimation =  CABasicAnimation(keyPath: "transform.rotation")
                animation.toValue = M_PI * 2
                animation.duration = 0.75
                animation.repeatCount = MAXFLOAT
                animation.removedOnCompletion = false
                iconView.layer.addAnimation(animation, forKey: nil)
                
                //往下偏移
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.scrollView?.contentInset.top = self.scrollView!.contentInset.top + self.pullDownRefreshHight
                })
                refreshBlock?()
            }
            
        }
    }
    var scrollView: UIScrollView?
    
    // MARK: - 系统方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(frame: CGRect) {
        let frame = CGRectMake(0, -pullDownRefreshHight, UIScreen.mainScreen().bounds.size.width, pullDownRefreshHight)
        super.init(frame: frame)
//        self.backgroundColor = UIColor.cyanColor()
        self.setupUI()
    }
    //移除监听
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    //监听UISScollView的偏移
    override func willMoveToSuperview(newSuperview: UIView?) {
        //判断父容
        if let scrollView = newSuperview as? UIScrollView {
            print("添加成功")
            self.scrollView = scrollView
            //监听父控件的偏移
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        }
    }
    //实现监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        self.scrollView = object as? UIScrollView
        let offset = self.scrollView?.contentOffset
        //偏移值
        let offsetY = offset!.y
//        print("父控件正在偏移\(offsetY)")
        if scrollView!.dragging {
            if offsetY >= -(pullDownRefreshHight + scrollView!.contentInset.top) && self.courrentState == .Pulling {
                //下啦刷新
                self.courrentState = .Normal
                print("下啦刷新")
            } else if offsetY < -(pullDownRefreshHight + scrollView!.contentInset.top) && self.courrentState == .Normal {
                print("松手刷新")
                self.courrentState = .Pulling
            }
        } else {
            if courrentState == .Pulling {
                print("正在刷新")
                courrentState = .Refreshing
            }
        }
    }
    // MARK: - 自定义的方法
    private func setupUI() {
        //添加子控件
        addSubview(iconView)
        addSubview(lable)
        //取消自动约束
        iconView.translatesAutoresizingMaskIntoConstraints = false
        lable.translatesAutoresizingMaskIntoConstraints = false
        //设置约束
        //图片的约束
        self.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -60))
        //label 的约束
        self.addConstraint(NSLayoutConstraint(item: lable, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: lable, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 20))
        
    }

    // MARK: - 添加子控件
    private lazy var iconView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var lable: UILabel = {
        let label = UILabel()
        label.text = "下拉刷新"
        label.font = UIFont.systemFontOfSize(18)
        return label
    }()
}
